# -*- coding: utf-8 -*-

from osv import fields,osv
from osv.orm import browse_record
import tools
from functools import partial
import pytz
import pooler
from tools.translate import _
import datetime
from service import security
import netsvc

class aas_news(osv.osv):
    
    def _get_users_ids(self, cr, uid, column, list_ids):
        res = []
        list_ids_sql = tuple(list_ids + [-1, -1])
        sql = '''
            SELECT id
            FROM res_users
            WHERE %s IN %s
        ''' % (column, list_ids_sql)
        cr.execute(sql)
        if cr.rowcount > 0:
            res = [id for (id,) in cr.fetchall()]
        return res
    
    def function_users(self, cr, uid, ids, field_name, args, context=None):
        res = {}
        all_users_ids = []
        sql = '''
            SELECT id
            FROM res_users
        '''
        cr.execute(sql)
        if cr.rowcount > 0:
            all_users_ids = [id for (id,) in cr.fetchall()]
            
        for news in self.browse(cr, uid, ids, context=context):
            users_ids = []
            users_ids.extend(all_users_ids)
            if news.profiles:
                list_ids = [o.id for o in news.profiles]
                users_ids = list(set(users_ids).intersection(set(self._get_users_ids(cr, uid, 'profile_id', list_ids))))
            if news.degrees:
                list_ids = [o.id for o in news.degrees]
                users_ids = list(set(users_ids).intersection(set(self._get_users_ids(cr, uid, 'degree_id', list_ids))))
            if news.atypes:
                list_ids = [o.id for o in news.atypes]
                users_ids = list(set(users_ids).intersection(set(self._get_users_ids(cr, uid, 'atype_id', list_ids))))
            if news.sessions:
                list_ids = [o.id for o in news.sessions]
                users_ids = list(set(users_ids).intersection(set(self._get_users_ids(cr, uid, 'session_id', list_ids))))
            if news.classes:
                list_ids = [o.id for o in news.classes]
                users_ids = list(set(users_ids).intersection(set(self._get_users_ids(cr, uid, 'class_id', list_ids))))
            if news.depts:
                list_ids = [o.id for o in news.depts]
                users_ids = list(set(users_ids).intersection(set(self._get_users_ids(cr, uid, 'dept_id', list_ids))))
            if news.specific_users:
                list_ids = [o.id for o in news.specific_users]
                users_ids = list(set(users_ids).intersection(set(self._get_users_ids(cr, uid, 'id', list_ids))))
            res[news.id] = list(set(users_ids))
        return res
    
    
    def function_email_receivers(self, cr, uid, ids, field_name, args, context=None):
        res = {}
        user_obj = self.pool.get('res.users')
#        print ''
#        print 'ids:', ids
        for news in self.browse(cr, uid, ids, context=context):
#            print '    news.users', news.users
            emails_str = ''
            users_ids = news.users
            if users_ids:
                sql = '''
                    SELECT email
                    FROM res_users
                    WHERE (email IS NOT NULL) AND (receive_emails = TRUE) AND (id IN %s)
                '''
                cr.execute(sql, (tuple(users_ids + [-1, -1]),))
                if cr.rowcount > 0:
                    emails = [email.strip() for [email,] in cr.fetchall() if email.strip()]
                    emails = list(set(emails))
                    emails_str = ','.join(emails)
            res[news.id] = emails_str
#            print '        res:', res 
        return res
    
    def function_content_short(self, cr, uid, ids, field_name, args, context=False):
        res = {}
        for obj in self.browse(cr, uid, ids, context=context):
            val = ''
            if obj.content:
                val = obj.content[:100]
                if len(obj.content) > 100:
                    val += '...'
            res[obj.id] = val
        
        return res
    
    _name = 'aas.news'
    _description = 'Thông báo'
    _columns = {
        'name': fields.char('Tiêu đề', size=256, required=True, readonly=True, states={'draft':[('readonly', False)]}),
        'creator': fields.many2one('res.users', 'Người tạo', readonly=True),
        'time_published': fields.datetime('Ngày giờ đăng', readonly=True),
        'content': fields.text('Nội dung', readonly=True, states={'draft':[('readonly', False)]}),
        'content_short': fields.function(function_content_short, method=True, type='char', size=100, string='Nội dung'),
        'profiles': fields.many2many('profile', 'aas_news_profiles', 'news_id', 'profile_id', 'Applied For Profiles', readonly=True, states={'draft':[('readonly', False)]}),
        'degrees': fields.many2many('aas.academic.degree', 'aas_news_degrees', 'news_id', 'degree_id', 'Applied For Academic Degrees', readonly=True, states={'draft':[('readonly', False)]}),
        'atypes': fields.many2many('aas.academic.type', 'aas_news_atypes', 'news_id', 'atype_id', 'Applied For Academic Types', readonly=True, states={'draft':[('readonly', False)]}),
        'sessions': fields.many2many('aas.academic.session', 'aas_news_sessions', 'news_id', 'session_id', 'Applied For Sessions', readonly=True, states={'draft':[('readonly', False)]}),
        'classes': fields.many2many('aas.class', 'aas_news_classes', 'news_id', 'class_id', 'Applied For Classes', readonly=True, states={'draft':[('readonly', False)]}),
        'depts': fields.many2many('aas.department', 'aas_news_depts', 'news_id', 'dept_id', 'Applied For Departments', readonly=True, states={'draft':[('readonly', False)]}),
        'specific_users': fields.many2many('res.users', 'aas_news_users_rel', 'news_id', 'user_id', 'Applied For Users', readonly=True, states={'draft':[('readonly', False)]}),
        'state': fields.selection((('draft', _('Đang soạn thảo')),
                                   ('published', _('Đã được đăng'))), string='Trạng thái', readonly=True),
        'emails_sent': fields.boolean('Đã gửi emails?', readonly=True),
        'users': fields.function(function_users, method=True, type='list', string='Users'),
        'email_receivers': fields.function(function_email_receivers, method=True, type='text', string='Emails of Receivers'),
    }
    _defaults = {
        'state': lambda *a: 'draft',
        'creator': lambda self, cr, uid, context: uid,
        'emails_sent': lambda *a: False,
    }
    _order = 'time_published desc, id desc'
    
    def action_publish(self, cr, uid, ids, context=None):
        vals = {'state': 'published', 'time_published': datetime.datetime.now()}
        res = self.write(cr, uid, ids, vals, context=context)
        return res
    
    def copy(self, cr, uid, id, default=None, context=None):
        if not default:
            default = {}
        default.update({'emails_sent': False, 'creator': uid, 'state': 'draft', 'time_published': False})
        return super(aas_news, self).copy(cr, uid, id, default, context=context)
    
    def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False):
        if not args:
            args = []
        if uid != 1:
            all_ids = []
            sql = '''
                SELECT id
                FROM aas_news
            '''
            cr.execute(sql)
            if cr.rowcount > 0:
                all_ids = [id for (id,) in cr.fetchall()]
            search_ids = []
            for news in self.browse(cr, uid, all_ids, context=context):
                if uid in news.users:
                    search_ids.append(news.id)
            args.append(('id', 'in', search_ids))
        res = super(aas_news, self).search(cr, uid, args, offset=offset, limit=limit, order=order, context=context, count=count)
        return res
    
    
    def send_news_notification_emails(self, cr, uid, context=None):
        print '****Inside function to send emails...'
        if not context: context = {}
        sql = '''
            SELECT id
            FROM aas_news
            WHERE (emails_sent = FALSE) AND (state IN ('published'))
        '''
        cr.execute(sql)
        if cr.rowcount > 0:
            ids = [id for (id,) in cr.fetchall()]
            property_obj = self.pool.get('trobz.property')
            property_name = 'Gửi emails khi đăng thông báo mới'
            property = property_obj._get_project_property_by_name(cr, uid, property_name)
            if not property:
                raise osv.except_osv(_('Lỗi!'), _('Không tìm thấy thuộc tính "%s"!' % (property_name,)))
            property_value = property.value
            send_email = False
            try:
                property_value = int(property_value)
                if property_value == 1:
                    send_email = True
            except: pass
            
            if send_email:
                email_template_obj = self.pool.get('poweremail.templates')
                mailbox_obj = self.pool.get('poweremail.mailbox')
                attachment_obj = self.pool.get('ir.attachment')
                
                name = 'Thông báo'
                template_ids = email_template_obj.search(cr, uid, [('name', '=', name)])
                if not len(template_ids):
                    raise osv.except_osv(_('Lỗi!'), _('Không tìm thấy mẫu email "%s"!' % (name,)))
                
                for id in ids:
                    emails_ids = email_template_obj.generate_mail(cr, uid, template_ids[0], [id], context=context)
                    attachments_ids = attachment_obj.search(cr, uid, [('res_model', '=', 'aas.news'), ('res_id', '=', id)], context=context)
                    mailbox_obj.write(cr, uid, emails_ids, {'pem_attachments_ids': [(6, 0, attachments_ids)]}, context=context)
                print 'Đang gửi emails cho các thông báo mới đã được đăng...'
                mailbox_obj.send_all_mail(cr, uid, context=context)
            self.write(cr, uid, ids, {'emails_sent': True}, context=context)
        return True
    
    
aas_news()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
